import  axios from 'axios'
import { Toast } from 'antd-mobile'

import { createBrowserHistory } from 'history'
var history = createBrowserHistory()

//设置拦截器
axios.interceptors.request.use((config)=>{
    //携带token请求头
    config.headers['Authorization'] = 'Bearer '+ localStorage.getItem('token');
    return config;
    
},(err)=>{
    return Promise.reject(err);
})

axios.interceptors.response.use((res)=>{
    return res;
},(err)=>{
    //处理错误状态码
    if( err.response.status == 401 ){
        // alert('身份验证失败!');
        Toast.show({
            icon: 'fail',
            content: '身份验证失败!',
          })
        //删除token
        localStorage.removeItem('token')
        //跳转到登录页 
        history.push('/login')
        history.go()
    }else if( err.response.status == 404 ){
        Toast.show({
            icon: 'fail',
            content: '访问路径有误!',
          })
    }else if( err.response.status == 500 ){
        Toast.show({
            icon: 'fail',
            content: '服务器内部错误!',
          })
    }
    return Promise.reject(err);
})

export default axios;